<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $selectpageFields = 'id,username,nickname,mobile';
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = json_decode($this->request->get('filter'), true);
            //$op = json_decode($this->request->get('op'), true);
            $map = [];
            if(isset($filter['is_vip'])){
                if($filter['is_vip'] == 1){
                    $map['vip_expire_time'] = ['egt', time()];
                }else{
                    $map['vip_expire_time'] = ['exp', Db::raw('IS NULL OR vip_expire_time <= "'.date('Y-m-d H:i:s', time()).'"')];
                }
                unset($filter['is_vip']);
            }
            //$this->request->get('filter', json_encode($filter));
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null,json_encode($filter));
            
            $list = $this->model
                ->with('group')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
            
            $now = time();
            foreach ($list as $k => $v) {
                //$v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                
                // 根据会员到期时间自动处理is_vip状态
                if($v->vip_expire_time) {
                    $expire_time = $v->vip_expire_time;
                    $v->is_vip = $expire_time > $now ? 1 : 0;
                } else {
                    $v->is_vip = 0;
                }
            }
            
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 设置讲师
     */
    public function set_teacher($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                $result = false;
                try {
                    $result = $row->allowField(true)->save($params);
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 查看消费记录
     */
    public function consume_log($ids = null)
    {
        $user = $this->model->find($ids);
        if (!$user) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isAjax()) {
            // 临时保存原始model
            $originalModel = $this->model;
            // 设置为消费记录model
            $this->model = new \app\common\model\UserConsumeLog;
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        
            $total = $this->model
                ->where($where)
                ->where('user_id', $ids)
                ->count();
                
            $list = $this->model
                ->where($where)
                ->where('user_id', $ids)
                ->order($sort ?: 'id', $order ?: 'desc')
                ->limit($offset, $limit)
                ->select();
                
            // 计算筛选条件下的总收支
            $totalAmount = $this->model
                ->where($where)  // 使用相同的where条件
                ->where('user_id', $ids)
                ->sum('amount');
                
            // 恢复原始model
            $this->model = $originalModel;   
            return json([
                'total' => $total, 
                'rows' => $list,
                'extend' => [
                    'total_amount' => $totalAmount
                ]
            ]);
        }
        
        // 获取用户总收支
        $totalAmount = \think\Db::name('user_consume_log')
            ->where('user_id', $ids)
            ->sum('amount');
            
        $this->view->assign([
            "user" => $user,
            "total_amount" => $totalAmount
        ]);
        return $this->view->fetch();
    }
}
